package com.heima.kafka.sample;

import org.apache.kafka.common.protocol.types.Field;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;

public class KafkaStreamQuickStart {

    public static void main(String[] args) {

        //kafka配置
        Properties properties = new Properties();
        properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //消息的key和value的转换器
        properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        //应用id
        properties.put(StreamsConfig.APPLICATION_ID_CONFIG,"app-001");

        //
        StreamsBuilder streamsBuilder = new StreamsBuilder();

        //流式计算
        processorStream(streamsBuilder);


        //创建一个KafkaStram对象
        KafkaStreams streams = new KafkaStreams(streamsBuilder.build(),properties);

        //开启流式计算
        streams.start();
    }

    /**
     * 流式计算
     * @param streamsBuilder
     */
    private static void processorStream(StreamsBuilder streamsBuilder) {
        //从哪个topic中接收消息,创建stream对象
        KStream<String, String> stream = streamsBuilder.stream("stream-input-topic");

        //流式处理
        /**
         * 把消息的内容切割之后，把一个一个的单词装入到集合中
         * hello kafka
         */
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                String[] split = value.split(" ");
                return Arrays.asList(split);

            }
        })
                //按照单词聚合
                .groupBy((key,value)->value)
                //时间窗口,每5秒聚合一次
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //计算单词的个数，消息的key和value会发生变化：key:单词，value:个数（long）
                .count()
                .toStream()
                //把消息的类型转换
                .map((key,value)->{

                    return new KeyValue<>(key.key().toString(),value.toString());
                }).to("stream-out-topic");

    }
}
